package com.whut.whw.find;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.whut.whw.R;
import com.whut.whw.base.BaseFragment;
import com.whut.whw.constant.ConfigConsts;
import com.whut.whw.goodsdetail.GoodsDetailAndDisposeActivity;
import com.whut.whw.model.BackResult;
import com.whut.whw.model.Goods;
import com.whut.whw.util.BackResultCallback;
import com.whut.whw.util.GsonUtils;
import com.whut.whw.util.LogUtils;
import com.whut.whw.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.whut.whw.constant.ConfigConsts.GOODS_LIST_URL;
import static com.whut.whw.constant.ConfigConsts.MYGOODS_PAGESIZE;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/09
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class TabFragment extends BaseFragment {
    private RecyclerView mRecyclerView;
    public static final String TITLE = "title";
    // 标志当前Tab页
    private String mTitle = "Defaut Value";
    private static final String TAG = "TabFragment";
    final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
    // recycleview适配器
    private FindGoodsListAdapter adapter;
    // recycleview适配器的数据源
    private List<Goods> list = new ArrayList<>();
    // 标志是否正在执行获取“上拉加载数据”的操作
    private boolean isLoading;
    // 当前显示页码
    private int currentPage = 1;
    // 用户编号
    private String yhbh;

    /**
     * 绑定布局，初始化控件
     *
     * @param inflater
     * @return
     */
    @Override
    public View initView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_main_tab, null);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.id_stickynavlayout_innerscrollview);
        LogUtils.d(TAG, "initView:" + (mRecyclerView == null));
        return rootView;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initRecycleView();
        //获取用户编号
        SharedPreferences sp = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        yhbh = sp.getString("yhbh", "");
    }

    private void initRecycleView() {
        //设置布局管理器
        mRecyclerView.setLayoutManager(layoutManager);
//设置adapter
//        adapter = new MyGoodsListAdapter(getContext(), list);
        adapter = new FindGoodsListAdapter(getContext(), list);
        mRecyclerView.setAdapter(adapter);
//设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//添加分割线
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
//                DividerItemDecoration.VERTICAL));
        // 控件加载完后再加载数据
        mRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                getRefreshFromServer();
            }
        }, 1000);
    }

    /**
     * 从服务器上获取刷新数据
     */
    private void getRefreshFromServer() {
        currentPage = 1;
        isLoading = false;
        getDataFromServer();
        /*try {
            LogUtils.d(TAG, "okhttp开始执行");
            *//*Response response = OkHttpUtils
                    .get()
                    .url(GOODS_LIST_URL)
                    .addParams("type", TITLE)
                    .addParams("currentPage", currentPage + "")
                    .addParams("pageSize", MYGOODS_PAGESIZE + "")
                    .build()
                    .execute();
            if (response.isSuccessful()) {
                LogUtils.d(TAG,response.body().string());
            } else {
                LogUtils.d(TAG,"error");

            }
            LogUtils.d(TAG,"okhttp执行完成");*//*
            OkHttpUtils.post()
                    .url(GOODS_LIST_URL)
                    .addParams("type", mTitle)
                    .addParams("currentPage", currentPage + "")
                    .addParams("pageSize", MYGOODS_PAGESIZE + "")
                    .addParams("yhbh",yhbh)
                    .build()
                    .execute(new BackResultCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.d(TAG, e.toString());
                        }

                        @Override
                        public void onResponse(BackResult response, int id) {
                            Log.d(TAG, response.getData());
                            Log.d(TAG, response.getMsg());
                            Log.d(TAG, response.isSuccess() + "");
                            //如果请求成功
                            if (response.isSuccess()) {
                                List<Goods> list = GsonUtils.jsonToList(response.getData(), Goods.class);
                                if (list.size() < MYGOODS_PAGESIZE) {
                                    // 已经到底
                                    appendIsNoLoading(true);
                                } else {
                                    appendIsNoLoading(false);
                                }
                                adapter.updateData(list);
                                currentPage++;//页码+1
                            } else {// 请求失败
                                ToastUtils.showShort(R.string.network_error);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            //LogUtils.d(TAG,e.getMessage());
            ToastUtils.showShort(R.string.network_error);
        }*/
    }

    /**
     * 刷新操作时候判断下拉刷新状态和显示
     *
     * @param flag true:再无数据加载；false:还有数据
     */
    private void appendIsNoLoading(boolean flag) {
        // 每次加载完数据后都要更新适配器通知数据源改变，都要设置recyclerview的尾布局显示什么
        isLoading = flag;
        // 每次加载完数据后都要设置尾布局显示时是否查数据库
        adapter.setFooterFlag(flag);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTitle = getArguments().getString(TITLE);
        }
    }

    @Override
    public void setListener() {
        adapter.setOnItemClickLitener(new FindGoodsListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                getUiDelegate().toastShort("click" + adapter.getDatas().get(position).toString());
                // 跳转到物品详情页
                Bundle data = new Bundle();
                data.putString("id", adapter.getDatas().get(position).getMs());
                if (position % 2 == 0) {
                    data.putInt("pageFlag", ConfigConsts.GOODS_DETAIL_FLAG);
                } else {
                    data.putInt("pageFlag", ConfigConsts.DISPOSE_EXCHANGE_FLAG);
                }
                Intent intent = new Intent(getContext(), GoodsDetailAndDisposeActivity.class);
                intent.putExtras(data);
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        // 上拉加载更多
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = FindFragment.getmRefresh().isRefreshing();
                    if (isRefreshing) {// SwipeRefreshLayout正在刷新
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        getMoreDataFromServer();
                    }
                }
            }
        });
    }

    /**
     * 上拉加载更多数据
     */
    private void getMoreDataFromServer() {

        getDataFromServer();
    }

    /**
     * 从服务器获取数据
     */
    private void getDataFromServer() {
        try {
            LogUtils.d(TAG, "okhttp开始执行");
            OkHttpUtils
                    .post()
                    .url(GOODS_LIST_URL)
                    .addParams("type", mTitle)
                    .addParams("currentPage", currentPage + "")
                    .addParams("pageSize", MYGOODS_PAGESIZE + "")
                    .addParams("yhbh",yhbh)
                    .build()
                    .execute(new BackResultCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.d(TAG, e.toString());
                        }

                        @Override
                        public void onResponse(BackResult response, int id) {
                            Log.d(TAG, response.getData());
                            Log.d(TAG, response.getMsg());
                            Log.d(TAG, response.isSuccess() + "");
                            //如果请求成功
                            if (response.isSuccess()) {
                                List<Goods> list = GsonUtils.jsonToList(response.getData(), Goods.class);
                                if (list.size() < MYGOODS_PAGESIZE) {
                                    // 已经到底
                                    appendIsNoLoading(true);
                                } else {
                                    appendIsNoLoading(false);
                                }
                                adapter.appendData(list);
                                currentPage++;//页码+1
                            } else {// 请求失败
                                ToastUtils.showShort(R.string.network_error);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            //LogUtils.d(TAG,e.getMessage());
            ToastUtils.showShort(R.string.network_error);
        }
    }

    public static TabFragment newInstance(String title) {
        TabFragment tabFragment = new TabFragment();
        Bundle bundle = new Bundle();
        bundle.putString(TITLE, title);
        tabFragment.setArguments(bundle);
        return tabFragment;
    }

    /**
     * 根据父Fragment中传来的List更新RecycleView
     */
    public void refreshData() {
        getRefreshFromServer();
        FindFragment.getmRefresh().setRefreshing(false);
        mRecyclerView.scrollToPosition(0);
    }

}
